package com.common.web.exception;

import com.common.core.exception.code.WebErrorCode;
import com.common.core.results.VoidResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class CustomErrorController implements ErrorController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "error", method = {RequestMethod.GET, RequestMethod.POST})
    public VoidResult error(HttpServletRequest request) {
        Object errURL = request.getAttribute("javax.servlet.error.request_uri");
        HttpStatus status = this.getStatus(request);
        logger.error("服务异常状态:{},请求路径:{}", status.value(), errURL);
        switch (status) {
            case NOT_FOUND:
                return VoidResult.failed(WebErrorCode.S_ERROR_NO_HANDLER_FOUND);
            default:
                return VoidResult.failed(WebErrorCode.SYS_EXCEPTION_CODE);
        }
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }
}
